package com.lirh.data.mongodbdemo.dao;

import com.lirh.data.mongodbdemo.model.MongoTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

@Component
public class MongoTestDao {
    @Autowired
    private MongoTemplate mongoTemplate;

    public void saveTest(MongoTest mgtest) {
        mongoTemplate.save(mgtest);
    }

    public MongoTest findTestByName(String name) {
        Query name1 = new Query(Criteria.where("name").is(name));
        MongoTest one = mongoTemplate.findOne(name1, MongoTest.class);
        return one;
    }

    public void updateTest(MongoTest test) {
        Query id = new Query(Criteria.where("id").is(test.getId()));
        Update update = new Update().set("age", test.getAge()).set("name", test.getName());
        mongoTemplate.updateMulti(id,update,MongoTest.class);
    }

    public void deleteTestById(Integer i) {
        Query id = new Query(Criteria.where("id").is(i));
        mongoTemplate.remove(id,MongoTest.class);
    }
}
